package megrez.oss.local.web;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import megrez.oss.common.FileNameException;
import megrez.oss.common.FileNameHelper;
import megrez.oss.local.domain.MetadataRepository;
import megrez.oss.local.domain.MetadataService;

/**
 * 元数据API接口
 *  
 * @author Lucky Yang
 * @since 2.6.9
 */
@RestController
@RequestMapping("/v1/metadatas")
public class MetadataResource {
    @Autowired
    private MetadataRepository metadataRepo;
    @Autowired
    private MetadataService metadataSrc;


    @GetMapping("/{id}")
    public MetadataVO getById(@PathVariable String id) {
        return MetadataVO.withPO(metadataSrc.findById(id));
    }

    @GetMapping("/ids")
    public List<MetadataVO> getByIds(@RequestParam(value="ids") Set<String> ids) {
        return metadataRepo.findAllById(ids).stream().map(MetadataVO::withPO).collect(Collectors.toList());
    }

    @PatchMapping(value = "/{id}")
    public MetadataVO update(@PathVariable String id, @RequestParam(value="name") String name) {
        if (!FileNameHelper.validate(name)) {
            throw new FileNameException();
        }
        return MetadataVO.withPO(metadataSrc.update(id, name));
    }   
}
